<!DOCTYPE html>
<html lang="zh-cn">
  <%- include('layout/head'); -%>

  <body>
    <%- include('layout/nav'); -%>

    <div class="container my-5">
      <div class="row">
        <div class="col-md-6 mx-auto">
          <h1 class="text-center text-uppercase py-5">
            <span style="letter-spacing: 12px; font-weight: 100">
              Web<span style="font-weight: 300">socket</span>
            </span>
          </h1>

          <div
            id="messages"
            class="messages mb-4"
            style="height: 55vh; overflow-y: auto"
          ></div>
        </div>
      </div>
      <div class="row">
        <div class="col-md-6 mx-auto mb-4 fixed-bottom">
          <input id="message" type="text" class="form-control" />
        </div>
      </div>
    </div>

    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://cdn.bootcss.com/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <script src="/javascripts/socket.io.js"></script>
    <script>
      const socket = io();

      socket.on("connect", () => {
        console.log("连接成功");
        socket.emit("setUsername", "<%= username %>");
      });

      $("#message").keyup(function (event) {
        if (event.keyCode === 13) {
          event.preventDefault();
          const message = $(this)
            .val()
            .replaceAll("<", "&lt;")
            .replaceAll(">", "&gt;");
          $(this).val("");

          socket.emit("message", message);
        }
      });

      socket.on("message", (data) => {
        console.log("接受了来自服务器的消息");
        $("#messages").append(`
        <div class="message my-4 d-flex">
          <div class="mr-2">
            <small class="text-black-50">${data.username}: </small>
          </div>
          <div>
            ${data.message}
          </div>
        </div>
      `);

        $("#messages")
          .stop()
          .animate(
            { scrollTop: $("#messages").height() + $("#messages").scrollTop() },
            "slow"
          );
      });
    </script>
  </body>
</html>
